import json
import requests
import logging
from requests.utils import requote_uri


def work_order_cloud_bill(year: str, month: str, timeout: int = 20):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic eXVud2VpLmFwaTpDcWhUY2ZvOTZSNUE=}'
    }
    res = requests.get(f'https://sa.welab-inc.com/api/aliyun/gaap/check/resource?year={year}&month={month}',
                       headers=headers, timeout=timeout)
    res.encoding = 'utf-8'
    if res.status_code != 200:
        logging.error(res.text)
        return False
    else:
        return json.loads(res.text)


def welab_users(department_id: int, timeout: int = 20):
    headers = {
        'Content-Type': 'application/json',
        'authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJJRCI6Ijc3ZDljZjc1LWFhOGEtNDRlYy1iN2Q4LTY4NzI3YjhkNDAxZiIsIlVzZXJuYW1lIjoiYm9sbC5sYWkiLCJleHAiOjE2NDk4MTQyNjcsImlhdCI6MTY0OTcyNzg2NywibmJmIjoxNjQ5NzI3ODY3fQ.PR-9rH4lp8bD7GK7Ggmhd3AAfBy1kH-jwgZtMKK8me9bTdrAlGowBR8LrwNBZhQ4sA6xrhWJ6iVAxkVvFGNlZQ'
    }

    res = requests.get(
        f'https://cmdb.welab-inc.com/api/v1/users?username=&name=&query_value=&department_id={department_id}&role_ids=&status=0&current=1&page_size=100',
        headers=headers, timeout=timeout)
    res.encoding = 'utf-8'
    if res.status_code != 200:
        logging.error(res.text)
        return False
    else:
        return json.loads(res.text)


def welab_departments(timeout: int = 20):
    headers = {
        'Content-Type': 'application/json',
        'authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJJRCI6Ijc3ZDljZjc1LWFhOGEtNDRlYy1iN2Q4LTY4NzI3YjhkNDAxZiIsIlVzZXJuYW1lIjoiYm9sbC5sYWkiLCJleHAiOjE2NDk4MTQyNjcsImlhdCI6MTY0OTcyNzg2NywibmJmIjoxNjQ5NzI3ODY3fQ.PR-9rH4lp8bD7GK7Ggmhd3AAfBy1kH-jwgZtMKK8me9bTdrAlGowBR8LrwNBZhQ4sA6xrhWJ6iVAxkVvFGNlZQ'
    }

    res = requests.get(f'https://cmdb.welab-inc.com/api/v1/departments',
                       headers=headers, timeout=timeout)
    res.encoding = 'utf-8'
    res.encoding = 'utf-8'
    if res.status_code != 200:
        logging.error(res.text)
        return False
    else:
        return json.loads(res.text)


def welab_departments_tree(timeout: int = 20):
    headers = {
        'Content-Type': 'application/json',
        'authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJJRCI6Ijc3ZDljZjc1LWFhOGEtNDRlYy1iN2Q4LTY4NzI3YjhkNDAxZiIsIlVzZXJuYW1lIjoiYm9sbC5sYWkiLCJleHAiOjE2NDk4MTQyNjcsImlhdCI6MTY0OTcyNzg2NywibmJmIjoxNjQ5NzI3ODY3fQ.PR-9rH4lp8bD7GK7Ggmhd3AAfBy1kH-jwgZtMKK8me9bTdrAlGowBR8LrwNBZhQ4sA6xrhWJ6iVAxkVvFGNlZQ'
    }

    res = requests.get(f'https://cmdb.welab-inc.com/api/v1/departments/tree',
                       headers=headers, timeout=timeout)
    res.encoding = 'utf-8'
    return json.loads(res.text)


def work_order_category(category_name: str, start_time: str, end_time: str, timeout: int = 20):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic eXVud2VpLmFwaTpDcWhUY2ZvOTZSNUE=}'
    }
    res = requests.get(
        f'https://sa.welab-inc.com/api/workorder/tickets?page=1&per_page=100&sort=-created_on&category_name={requote_uri(category_name)}&all=true&start={start_time}&end={end_time}',
        headers=headers, timeout=timeout)
    res.encoding = 'utf-8'
    if res.status_code != 200:
        logging.error(res.text)
        return False
    else:
        return json.loads(res.text)


if __name__ == "__main__":
    from pprint import pprint

    # pprint(work_order_category("【云资源】容器申请"))
    # pprint(work_order_category("【云资源】容器变更"))

    from common.database import SessionLocal
    from app.expense_quota.models import ExpenseQuotaUserInfo
    from app.expense_quota.models import ContainerQuota
    from app.expense_quota.utils import welab_users

    session = SessionLocal()
    quota = []

    for category in ["【云资源】容器申请","【云资源】容器变更","【云资源】容器回收"]:

        for item in work_order_category(category, "2022-02-03+00:00:00", "2022-03-31+00:00:00").get("data").get("items"):
            if item.get("operators")[-1].get("status"):
                print(item.get("id"))
                print(item.get("title"))
                print(category)
                print(item.get("created_by"))
                resource_ownership = ExpenseQuotaUserInfo.get_department_by_username(session, item.get("created_by"))
                print(resource_ownership)
                quota.append({"work_order_id": item.get("id"),
                              "title": item.get("title"),
                              "type": category,
                              "creator": item.get("created_by"),
                              "resource_ownership": resource_ownership.get("department"),
                              "create_year": "2022",
                              "create_month": "03"})
        ContainerQuota.saves(session, quota)

    # print(item.get(""))

    session.close()
